<template>
    <div class="container">
        <div>
            <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :md="5" :lg="5" v-if="userRoleValue!=8">
                    <div class="grid-content bg-purple">
                        <div class="left-box">
                            <div class="left-title">组织资源</div>
                            <div>
                                <el-tree
                                        :data="tagsList"
                                        :props="props"
                                        :load="loadNode"
                                        lazy
                                        check-strictly
                                        highlight-current
                                        show-checkbox
                                        node-key="id"
                                        ref="tree"
                                        @check-change="treeChange"
                                        @node-expand="handleNodeClick"
                                        @node-click="handleNodeClick">
                                </el-tree>
                            </div>
                        </div>
                    </div>
                </el-col>
                <el-col :xs="24" :sm="24" :md="userRoleValue!=8?19:24" :lg="userRoleValue!=8?19:24">
                    <div class="grid-content bg-purple">
                        <div class="right-box">
                            <div class="left-title">
                                <div>设备列表</div>
                                <div style="display: flex;">
                                    <el-input placeholder="请输入设备名称/IMEI" v-model="searchKey" class="input-with-select">
                                        <el-button slot="append" icon="el-icon-search" @click="searchEquiment">查询</el-button>
                                    </el-input>
                                </div>
                            </div>
                            <div>
                                <div class="list-div">
                                    <!--<template>-->
                                        <!--<span class="label-span">设备种类：</span>-->
                                        <!--<el-select v-model="deviceType" placeholder="请选择" @change="selectDeviceType">-->
                                            <!--<el-option-->
                                                    <!--v-for="item in options"-->
                                                    <!--:key="item.typeId"-->
                                                    <!--:label="item.typeName"-->
                                                    <!--:value="item.typeId">-->
                                            <!--</el-option>-->
                                        <!--</el-select>-->
                                    <!--</template>-->
                                    <!--<div style="float: right;margin-right: 50px;">-->
                                        <!--<el-checkbox v-model="checked" @change="checkedTimeingData">实时刷新</el-checkbox>-->
                                    <!--</div>-->
                                    <div class="message-tip message-tip-err" v-if="connectErrTxt" @click="closeMesTip">
                                        <div>{{connectErrTxt}}</div>
                                    </div>
                                </div>
                                <!--<div class="list-div">-->
                                    <!--<span class="label-span">群控：</span>-->
                                    <!--<template>-->
                                        <!--<el-button type="success">告警</el-button>-->
                                        <!--<el-button type="success">打开</el-button>-->
                                        <!--<el-button type="success">关闭</el-button>-->
                                        <!--<el-button type="success">关告警</el-button>-->
                                    <!--</template>-->
                                <!--</div>-->
                                <div class="list-div" style="padding: 0 10px;">
                                    <template>
                                        <el-table stripe :data="tableData" border style="width: 100%" @row-click="handleClickRow">
                                            <el-table-column prop="deviceLocation" width="250" label="设备位置"></el-table-column>
                                            <el-table-column prop="deviceCode" width="180" label="IMEI"></el-table-column>
                                            <el-table-column prop="deviceName" width="150" label="设备名称"></el-table-column>
                                            <el-table-column prop="realData" width="100" label="实时数据"></el-table-column>
                                            <el-table-column prop="deviceState" width="80" label="在线状态"></el-table-column>
                                            <!--<el-table-column prop="warnningMessage" :formatter="formatVal" width="100" label="通断状态"></el-table-column>-->
                                            <el-table-column prop="realDataUpdateTime" :formatter="formatTime" width="150" label="更新时间"></el-table-column>
                                            <!--<el-table-column prop="concentratorName" width="100" label="集中器"></el-table-column>-->
<!--                                            <el-table-column prop="warnningMessage" width="100" label="告警信息"></el-table-column>-->
                                            <el-table-column prop="functions" label="设备参数" fixed="right">
                                                <template slot-scope="scope">
                                                    <!--<el-button v-for="(item,index) in scope.row.functions" :key="item.functionId" size="mini" class="button-style" @click="clickBtn(scope.row,index)">{{item.functionName}}</el-button>-->
<!--                                                    <el-button size="mini" class="button-style">打开</el-button>-->
<!--                                                    <el-button size="mini" class="button-style">关闭</el-button>-->
                                                    <el-button type="text">设备参数</el-button>
<!--                                                    <el-button size="mini" class="button-style" style="background-color: #67C23A;">点抄</el-button>-->
<!--                                                    <el-button size="mini" class="button-style" style="background-color: #e6a23c;" @click="clickBtn">历史数据</el-button>-->
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                        <div class="pagination">
                                            <el-pagination background @current-change="handleCurrentChange" layout="prev, pager, next" :total="page_total" :page-size="page_size"></el-pagination>
                                        </div>
                                    </template>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>
        <div>
            <el-dialog title="设备历史数据" :visible.sync="dialogTableVisible">
                <template>
                    <div class="block">
                        <div class="demonstration">开始时间：</div>
                        <el-date-picker
                                v-model="value1"
                                type="datetime"
                                placeholder="选择日期时间">
                        </el-date-picker>
                    </div>
                    <div class="block">
                        <div class="demonstration">结束时间：</div>
                        <el-date-picker
                                v-model="value1"
                                type="datetime"
                                placeholder="选择日期时间">
                        </el-date-picker>
                    </div>
                    <div class="block">
                        <template>
                            <div class="demonstration">设备种类：</div>
                            <el-select v-model="deviceType" placeholder="请选择" @change="selectDeviceType">
                                <el-option
                                        v-for="item in options"
                                        :key="item.typeId"
                                        :label="item.typeName"
                                        :value="item.typeId">
                                </el-option>
                            </el-select>
                        </template>
                    </div>
                    <div class="block">
                        <el-button type="primary" icon="el-icon-search">查询</el-button>
                    </div>
                </template>
                <el-table  stripe :data="tableData" border>
                    <el-table-column property="date" label="序号" width="150"></el-table-column>
                    <el-table-column property="name" label="时间" width="200"></el-table-column>
                    <el-table-column property="address" label="表底读数"></el-table-column>
                </el-table>
                <div slot="footer" class="dialog-footer">
                    <el-button type="danger" icon="el-icon-switch-button" @click="dialogTableVisible = false">关闭</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import {regionalRoot,getSubOrgList,getDeviceTypeList,getDeviceMonitorList,querAllDevicesByUserId} from  '../../../api/index';
    import {famatDatesTimes} from '../../common/com';
    import {apiLoading} from '../../../config/index' //全局的页面跳转loading是否启用
    export default {
        name: "equipmentMonitoring",
        data () {
            return {
                options: [],
                deviceType: '',
                tableData: [],
                tagsList:[],
                demoData:'',
                clickedId:'',
                lazyInitData:[],
                lazyNode:null,
                lazyResolve:null,
                clickNode:null,
                clikData:null,
                props: {
                    label: 'orgName',
                    children: 'zones',
                    isLeaf: 'leaf'
                },
                connectErrTxt:'',
                dialogTableVisible:false,
                value1:'',
                cur_page:1,
                page_size:15,
                page_total:1,
                curr_id:"",
                setTimer:null,
                timerLength: 1000*60*40,//40分钟
                checked:false,
                typeId:'',
                userRoleValue:'',
                searchKey:''
            }
        },
        created(){
            this.userRoleValue = localStorage.getItem('uer_role_value')
            if(this.userRoleValue!=8){
                this.getData();
            }else{
                this.querAllDevicesByUserId()
            }

            this. getDeviceTypeOne();

        },
        beforeDestroy(){
            this.paramTimerClear
        },

        watch:{
            // globleIsConnet:function (val) {
            //     console.log(val);
            // }
            $route(to,from){
                // if(this.$route.path == '/equipmentMonitoring')
                if(this.$route.path == '/home'){
                   // this.paramSetTimerInit()
                }else{
                   this.paramTimerClear
                }
            }
        },

        methods :{
            checkedTimeingData(val){
                if(val){
                    this.timerLength = 1000*60*2
                    this.paramSetTimerInit()
                }else{
                    this.timerLength = 1000*60*40
                    this.paramTimerClear
                }
            },
            paramSetTimerInit() {
                let $_this = this;
                this.setTimer = setInterval(function () {
                    if($_this.curr_id&&$_this.checked){
                        apiLoading.isShow = false
                        if(this.userRoleValue!=8){
                            $_this.getDeviceMonitorList($_this.curr_id)
                        }else{
                            $_this.querAllDevicesByUserId()
                        }
                    }
                }, $_this.timerLength)
            },
            paramTimerClear() {
                clearInterval(this.setTimer);
                this.setTimer = null;
            },
            loadNode(node, resolve) {
                this.lazyNode = node;
                this.lazyResolve = resolve;
                if (node.level === 0) {
                    return resolve(this.tagsList);
                }
                // if (node.level > 1) return resolve([]);

                setTimeout(() => {
                    console.log(this.clickedId)
                    getSubOrgList({
                        pid:this.clickedId
                    }).then((res)=>{
                        console.log(res)
                        this.lazyInitData = res.datas;

                        resolve(this.lazyInitData);
                    })


                }, 500);
            },
            formatTime(row, column, cellValue){
                return famatDatesTimes(cellValue);
            },
            //获取数据
            getData(){
                regionalRoot({

                }).then((res) =>{
                    // console.log(res)
                    var dataArr = new Array();
                    dataArr[0] = res.expandData.root;
                    dataArr[0]['children'] = res.expandData.childrens;
                    this.tagsList = dataArr;

                    this.clickedId = this.tagsList[0].id;
                    // console.log(dataArr)
                })
            },
            //获取树的子节点
            getSubOrgList(){
                console.log(this.clickedId)
                getSubOrgList({
                    pid:this.clickedId
                }).then((res)=>{
                    console.log(res)
                    this.lazyInitData = res.datas;
                })
            },
            //获取设备列表
            getDeviceMonitorList(oId){
                getDeviceMonitorList({
                    pageNum:this.cur_page,
                    pageSize:this.page_size,
                    orgId:oId,
                    typeId:this.typeId,
                    serchPara:this.searchKey
                }).then((res)=>{
                    console.log(res)
                    apiLoading.isShow = true
                    this.tableData = res.data.list;
                    this.page_total = res.data.total;
                })
            },
            //根据用户查询所有设备
            querAllDevicesByUserId(){
                querAllDevicesByUserId({
                    pageNum:this.cur_page,
                    pageSize:this.page_size,
                    serchPara:this.searchKey
                }).then((res)=>{
                    console.log(res)
                    apiLoading.isShow = true
                    this.tableData = res.data.list;
                    this.page_total = res.data.total;
                })
            },
            // 分页导航
            handleCurrentChange(val) {
                this.cur_page = val;
                // this.getDeviceMonitorList(this.curr_id);
                if(this.userRoleValue!=8){
                    this.getDeviceMonitorList(this.curr_id);
                }else{
                    this.querAllDevicesByUserId()
                }
            },
            clickBtn(row,i){
                event.stopPropagation()
                event.preventDefault()
                // this.dialogTableVisible = true;
                console.log(row)

                var str = 'action,'+row.concentrator+','+
                    row.deviceCode+','+
                    row.functions[i].typeId+','+
                    row.functions[i].orderNo+ ','+
                    row.functions[i].functionName+ ','+
                    row.functions[i].functionCode+ ',' +
                    row.deviceId ;
                console.log(str);

                this.socketApi.sendSock(this,str,(data)=>{
                    this.connectErrTxt = JSON.parse(data).message;
                    if(this.userRoleValue!=8){
                        this.getDeviceMonitorList(this.curr_id);
                    }else{
                        this.querAllDevicesByUserId()
                    }
                });
            },
            closeMesTip(){
                this.connectErrTxt="";
            },
            //树的节点点击事件
            handleNodeClick(data,node) {
                this.clikData = data;
                this.clickNode = node;

                this.$refs.tree.setCheckedNodes([data]);

                if(data.pid === 0){
                    this.clickedId = data.id;
                    this.demoData = data;
                    this.demoData['pname'] = data.orgName;
                    return ;
                }
                this.clickedId = data.id;
                this.demoData = data;
                this.demoData['pname'] = node.parent.data.orgName;
            },
            //获取设备类型下拉数据
            getDeviceTypeOne(){
                getDeviceTypeList({
                }).then((res) =>{
                    console.log(res)
                    this.options = res.datas;
                })
            },
            //树复选框点击
            treeChange(data,node,val){
                console.log(data)
                console.log(node)
                console.log(val)
                if(node){
                    this.$refs.tree.setCheckedNodes([data]);
                    this.curr_id = data.id;
                    this.cur_page = 1;
                    this.getDeviceMonitorList(data.id)
                }else{
                    this.tableData = [];
                    this.page_total = 1;
                    if(this.curr_id==data.id){
                        this.curr_id = "";
                    }
                }
            },
            //点击设备类型列表
            selectDeviceType(val){
                console.log(val)
                this.typeId = val;
                this.cur_page = 1;
                this.tableData = [];
                this.getDeviceMonitorList(this.curr_id);
            },
            formatVal(row, column, cellValue, index){
                return parseInt(cellValue)==1?'断开':parseInt(cellValue)==0?'通电':'';
            },
            handleClickRow(row,cell,e){
                console.log(1234,row,cell,e)
                sessionStorage.setItem('list_item',JSON.stringify(row))
                this.$router.push('/equimentparam')
            },
            //查询设备
            searchEquiment(){
                console.log(this.searchKey)
                if(this.userRoleValue!=8){
                    this.getDeviceMonitorList(this.curr_id);
                }else{
                    this.querAllDevicesByUserId()
                }

            }
        }
    }
</script>

<style scoped>
    .left-box,.right-box{
        border: 1px solid #409EFF;
        min-height: 800px;
    }
    .right-box{
        min-height: 500px;
    }
    .left-title{
        height: 40px;
        line-height: 40px;
        background-color: #409EFF;
        color: #fff;
        padding: 0 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .label-span{
        font-size: 14px;
        margin-right: 50px;
        margin-left: 10px;
    }
    .list-div{
        margin-top: 15px;
    }
    .button-style{
        padding: 2px 5px;
        margin-left: 0;
        background-color: #852b99;
        color: #fff;
        font-size: 12px;
    }
    .message-tip{
        margin: 5px 15px 30px;
        height: 50px;
        line-height: 50px;
        /*border-color: #eed3d7;*/
        font-size: 14px;
        padding: 0 20px;
    }
    .message-tip-success{
        color: #67C23A;
        background-color: #f0f9eb;
    }
    .message-tip-err{
        color: #b94a48;
        background-color: #f2dede;
    }
    .block{
        display: inline-block;
        margin-right: 20px;
        margin-bottom: 20px;
    }
    .demonstration{
        margin-bottom: 8px;
    }
</style>
